// vim: filetype=cpp

%TEX2D normalmap = pallot2DOT3
//%EX2D normalmap = FlatDOT3
%TEXCUBE refmap = galileo
%TEXCUBE ambientmap = galileoblur

%VERTEX_SHADER

attribute vec3 aTangent;
attribute vec3 aBitangent;
uniform vec3 uLightPos;

varying vec2 vTexCoord;
// Normal and light vector in tangent space
varying vec3 vNormal;
varying vec3 vLight;
varying vec3 vRotNorm;
varying vec3 vPos;

void main (void)
{
    vec4 Position;
    Position = gl_ModelViewMatrix * gl_Vertex;
    vPos = Position.xyz;
    gl_Position = gl_ProjectionMatrix * Position;
    
    vTexCoord = gl_MultiTexCoord0.st;

    // Direction to light
    vec3 es_light = vec3(gl_LightSource[0].position - Position);
    vec3 os_light = vec3(gl_ModelViewMatrixTranspose * vec4(es_light, 1));
    
    // In object space
    vLight = os_light;
    vNormal = gl_Normal;

    // In tangent space
    vec3 T = aTangent;
    vec3 B = aBitangent;
    vec3 N = gl_Normal;
    
    // Transform light vector to tangent space.
    vLight.x = dot(os_light, T);
    vLight.y = dot(os_light, B);
    vLight.z = dot(os_light, N);
    mat3 M;
    //mat3 M = mat3(T,B,N);
    M = mat3(T.x, B.x, N.x,
             T.y, B.y, N.y,
             T.z, B.z, N.z);
//     M = mat3(  cross(B,N).x, -cross(B,N).y,  cross(B,N).z,
//               -cross(N,T).x,  cross(N,T).y, -cross(N,T).z,
//                cross(T,B).x, -cross(T,B).y,  cross(T,B).z);
    M = mat3(  cross(B,N).x, -cross(N,T).x,  cross(T,B).x,
              -cross(B,N).y,  cross(N,T).y, -cross(T,B).y,
               cross(B,N).z, -cross(N,T).z,  cross(T,B).z);
    M = M * 1.0/( (T.x*B.y*N.z - T.z*B.y*N.x) +
                  (B.x*N.y*T.z - B.z*N.y*T.x) +
                  (N.x*T.y*B.z - N.z*T.y*B.x) );
                  
//     vLight = M*os_light;

    vLight = normalize(vLight);

    vRotNorm = gl_NormalMatrix*gl_Normal;
}

%FRAGMENT_SHADER

uniform sampler2D normalmap;
uniform samplerCube refmap;
uniform samplerCube ambientmap;

varying vec2 vTexCoord;
varying vec3 vNormal;
varying vec3 vLight;
varying vec3 vRotNorm;
varying vec3 vPos;

vec3 col2vec (in vec4 c) 
{
    return (c.xyz-vec3(.5)) * 2.0;
}

void main (void)
{
    vec3 L = normalize(vLight);
    //vec3 N = vec3(0,0,1);
    vec3 N = normalize(col2vec(texture2D(normalmap, vTexCoord.xy)));
//     vec3 L = vLight;
//     vec3 N = col2vec(texture2D(normalmap, vTexCoord.xy));
    vec3 V = normalize(-vPos);
    N = vRotNorm;
    vec3 R = V - (2.0*dot(V,N))*N;
    
    float d = dot(L, N);
    gl_FragColor = vec4(d,d,d,1.0);
//     gl_FragColor = vec4(vTexCoord.xy, 0,0);
//     gl_FragColor = vec4((d-.5)*2.0+1.0);

    
    gl_FragColor = textureCube(refmap, vRotNorm);

    float f = dot(V, vRotNorm);
    f *= f;

    vec3 paint = vec3(f,1.0-f, .3*f);
    vec3 ambient = textureCube(ambientmap, vRotNorm).xyz;
    vec3 ref = textureCube(refmap, R).xyz;

    gl_FragColor = vec4(paint*ambient+ref, 1);
    
    //gl_FragColor = vec4(V, 1);
}


